package MapReduce.Demo1_WordCount;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * @Author lixin
 * @Date 2023/3/15 9:10
 */
public class WordCountReducer extends Reducer<Text, IntWritable,Text, IntWritable> {

    IntWritable outValue = new IntWritable();

    @Override
    protected void setup(Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        System.out.println("Reducer 类里的 setUp 方法");
    }

    /**
     * 经过shuffle进入到Reducer的数据格式
     *      hello (1,1,1,1)
     *      world (1)
     * @param key
     * @param values
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {

        System.out.println("当前的key："+key);

        //初始化每个单词的初始数量
        int sum = 0;

        //遍历每个单词的value，进行相加计数
        for (IntWritable value : values) {
            //因为value是IntWritable类型，必须通过get转成int类型才可以相加
            sum += value.get();
        }

        outValue.set(sum);

        context.write(key,outValue);

    }

    @Override
    protected void cleanup(Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        System.out.println("Reducer 类里的 cleanUp 方法");
    }
}
